#!/usr/bin/env python
#
# Directory listing to index.html
# Author:  Yotam Medini  yotam.medini@gmail.com -- Created: 2011/December/17

import os
import sys
import subprocess
import stat
import time


(eUndef, eDir, eLinkDir, eLink, eReg) = range(5)
e2s = {
    eDir: 'D',
    eLinkDir: 'LD',
    eLink: 'L',
    eReg: 'F'
    }

def fatal(msg):
    sys.stderr.write("Fatal: %s\n" % msg)
    sys.exit(1)


def isstat(en, predicate):
    e = False
    try:
        s = os.stat(en)
        e = predicate(s[stat.ST_MODE])
    except:
        e = False
    return e


def fexist(fn):
    "Check if fn exists as regular file"
    return isstat(fn, stat.S_ISREG)


def ymdhms(t):
    ta = time.gmtime(t)
    s = "%d/%02d/%02d %02d:%02d:%02d" % ta[0:6]
    return s


def cksum(fn):
    cmd = "cksum %s" % fn
    p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    rc = p.wait()
    if rc != 0:
        fatal("failed (rc=%d=0x%x) %s" % (rc, rc, cmd))
    outline = p.stdout.readline()
    v = int(outline.split()[0])
    return v


def fwstat(e):
    etype = eUndef
    estat = os.lstat(e)
    mode = estat[stat.ST_MODE]
    if stat.S_ISLNK(mode):
        etype = eLink
        estat = os.stat(e)
        mode = estat[stat.ST_MODE]
    t = ymdhms(estat[stat.ST_MTIME])
    sz = -1
    cks = -1
    if stat.S_ISREG(mode):
        if etype == eUndef:
            etype = eReg
        sz = estat[stat.ST_SIZE]
    elif stat.S_ISDIR(mode):
        etype = eDir if etype == eUndef else eLinkDir
    if sz >= 0:
        cks = cksum(e)
    if etype == "":
        ret = None
    else:
        ret = (etype, e, t, sz, cks)
    # sys.stdout.write("ret=%s\n" % str(ret))
    return ret


######
# Main
idxhtml = "index.html"
if fexist(idxhtml):
    sys.stderr.write("%s - Already exists\n" % idxhtml)
    sys.exit(1)


entries = os.listdir(".")
estats = []
for e in entries:
    es = fwstat(e)
    if not es is None:
        estats.append(es)
estats.sort()


fih = open(idxhtml, "w")
sys.stderr.write("%d entries\n" % len(entries))
basedn = os.getcwd().split('/')[-1]
title = "Directory Listing of: %s" % basedn
h1_title = "<em>Directory Listing of:</em> <strong>%s</strong>" % basedn
fih.write("""
<html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>%s</title>
    <style>
      td.ldetail {
         padding-left: 1em;
         padding-right: 1em;
         white-space: nowrap;
         text-align: left;
      }
      td.rdetail {
         padding-left: 1em;
         padding-right: 1em;
         white-space: nowrap;
         text-align: right;
      }
    </style>
  </head
<body>
<h1>%s</h1>

<table>
  <tr>
    <th class="ldetail">Type</th>
    <th class="ldetail">Name</th>
    <th class="ldetail">Last Modified</th>
    <th class="ldetail">Size</th>
    <th class="ldetail">Checksum</th>
  </tr>
"""[1:] % (title, h1_title))
for es in estats:
    # sys.stderr.write("es=%s\n" % str(es))
    fn = es[1]
    hlink = '<a href="%s">%s</a>' % (fn, fn)
    row = """
    <td class="rdetail">%s</td>
    <td class="ldetail">%s</td>
    <td class="ldetail">%s</td>
"""[1:] % (e2s[es[0]], hlink, es[2])
    if es[3] >= 0:
        row += """
    <td class="rdetail">%s</td>
    <td class="rdetail">%s</td>
"""[1:] % (es[3], es[4])
    fih.write("""
  <tr>
%s
  </tr>
"""[1:]
              % row)
fih.write("""
</table>
</body>
</html>
"""[1:])
fih.close()

sys.exit(0)
